package com.zenithsun.common.image.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.syzg.common.controller.BaseController;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.image.StorageRule;

@Controller
@RequestMapping("/path/image")
public class ImageController extends BaseController implements ServletContextAware {
	
	private File noExistFile = null;
	
	@Override
	public void setServletContext(ServletContext servletContext) {
	   String path = servletContext.getRealPath("zenithsun/jsp/image") + "/no_exist.jpg";
	   if (noExistFile == null) {
		   noExistFile = new File(path);
	   }
	}
	
	/**
	 * 初始化上传页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/init")
	public ModelAndView init() throws Exception {
		return new ModelAndView("/zenithsun/common/image/upload/init.jsp");
	}
	
	/**
	 * 初始化CKEditer编辑器上传页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/initCKEditerImageUpload")
	public ModelAndView initCKEditerImageUpload() throws Exception {
		return new ModelAndView("/zenithsun/common/image/ckImageUpload.jsp");
	}
	
	@RequestMapping(value = "/deleteImages", produces = "application/json;charset=UTF-8")
	public @ResponseBody String deleteImages(String paths,HttpServletRequest request) throws Exception {
		OutMessage outMessage = new OutMessage();
		try {
			StorageRule sr=new StorageRule(request);
			String storePath=sr.getCurrProjectPath().replaceAll(request.getContextPath(), "");
			String[] idarray=paths.split(";");
			int count=0;
			for(String path:idarray){
				File file=new File(storePath+path);
				if(file.delete()){
					count++;
				}
			}
			outMessage.setContent(count);
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent(e.getMessage());
		}
		return JSON.toJSONString(outMessage);
	}
	
	/**
	 * 上传新闻图片<br/>
	 * 该方法存在性能问题，每上传一张保存一条数据到后台，会造成频繁读取数据库<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-6 09:32:51
	 * @param request （请求对象）
	 * @param newsinfoId  （新闻ID）
	 * @return @ResponseBody String (failure为失败，success为成功)
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadImage", produces = "application/json;charset=UTF-8")
	public @ResponseBody String picUpload(HttpServletRequest request) {
		OutMessage outMessage=new OutMessage();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> itr = multiRequest.getFileNames();
			if (!itr.hasNext()) {
				outMessage.setState(OutMessageState.Fail);
				return JSON.toJSONString(outMessage,SerializerFeature.WriteNullStringAsEmpty);
			}
			try {
				//加载文件存储规则
				StorageRule sr = new StorageRule(request);
				sr.setTempStore(false);
				//设置当前项目实际存储路径
				MultipartFile mpf = null;
				while (itr.hasNext()) {
					mpf = multiRequest.getFile(itr.next());
					sr.setFileName(mpf.getOriginalFilename());
					File file=new File(sr.GetNewsImageStorePath());
					//存储文件的目录是否存在，不存在则创建，否则会导致上传失败
					if(!file.getParentFile().exists()){
						file.getParentFile().mkdirs();
					}
					FileCopyUtils.copy(mpf.getBytes(),new FileOutputStream(file));
					outMessage.setState(OutMessageState.Success);
					outMessage.setContent((request.getContextPath()+StorageRule.newsSavePath+ sr.getRelativeStorePath()).replaceAll("\\\\", "/"));
				}
			} catch (IOException e) {
				outMessage.setState(OutMessageState.Fail);
				return JSON.toJSONString(outMessage,SerializerFeature.WriteNullStringAsEmpty);
			} catch (Exception e) {
				outMessage.setState(OutMessageState.Fail);
				return JSON.toJSONString(outMessage,SerializerFeature.WriteNullStringAsEmpty);
			}
		}
		String json=JSON.toJSONString(outMessage,SerializerFeature.WriteNullStringAsEmpty);
		return json;
	}
	
	
	
	@SuppressWarnings("rawtypes")
	@RequestMapping("/upload")
	public ResponseEntity upload(MultipartHttpServletRequest request) {
		 Iterator<String> itr =  request.getFileNames();
		 MultipartFile mpf = null;
		 while(itr.hasNext()){
			 mpf = request.getFile(itr.next()); 
			 String newFilenameBase = UUID.randomUUID().toString();
		     String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
		     String path = "D:/temp/dropzone/"+newFilenameBase + originalFileExtension;
		     try {
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path));
			}  catch (IOException e) {
				e.printStackTrace();
			} 
		 }
		 return new ResponseEntity<>("{}", HttpStatus.OK);
	}
	
	 @RequestMapping(value = "/thumbnail/{id}", method = RequestMethod.GET)
	  public void thumbnail(HttpServletRequest request ,HttpServletResponse response, @PathVariable String id) throws IOException {
		   File imageFile = new File("D:/img/"+id+".jpg");
		   if (!imageFile.exists()) {
			   imageFile = noExistFile;
		   }
		   InputStream is = new FileInputStream(imageFile);
		   IOUtils.copy(is, response.getOutputStream());
	  }
	
}
